﻿-- Author      : Thorwald Odin
-- Create Date : 12/7/2013 1:50:59 PM
local _, addon = ...; -- retrieve addon table

local L = addon.Locale;

do
	local timeZero = GetTime();
	local frame;
	local debugEvents = {};
	local maxDebugEvents = 100;
	local lastTime = 0;
	local timeAdjust = 0;

	local function Debug_UpdateData()
		local data = '';
		for i, v in ipairs(debugEvents) do
			if i <= maxDebugEvents and addon.db.DebugWatch[v.Type] then
				if addon.db.DebugWatch.Timestamp then
					data = data .. string.format("[%.3f seconds]", v.Time);
	--				data = data .. addon:Format("[{1}]", v.Time);
				end
				data = data .. addon:Format("({1}) :: {2}\n", v.Type, v.Message);
			end
		end
		if data == '' then
			data = L['There are no debug events on levels being watched.'];
		end
		frame.Data:SetText(data);
		frame.Data.Selected = false;
	end

	local function Debug_UpdateCheckButton(f)
		if f.Type and addon.db.DebugWatch[f.Type] ~= nil then
			f:SetChecked(addon.db.DebugWatch[f.Type]);
		end
	end

	local function Debug_FrameShow()
		Debug_UpdateData();
	end

	local function Debug_FrameHide()
		frame.Data:SetText('');
	--	frame.Options.Content:Hide();
	--	frame.Options.Content:ReleaseChildren();
	end

	local function Debug_CreateFrame()
		frame = getglobal("LootFilterDebugWindow");
		
		frame:SetScale(UIParent:GetEffectiveScale());
		
		frame:SetScript("OnShow", Debug_FrameShow);
		frame:SetScript("OnHide", Debug_FrameHide);
		
		frame.Data:SetScript("OnTextChanged", Debug_UpdateData);
	end

	function addon:Error(msg, ...)
		self:Debug("error", msg, ...);
		geterrorhandler()(self:Format(msg, ...));
	end

	function addon:Assert(exp, msg, ...)
		if not exp then
			self:Error("Assertion failed!\n" .. (msg or ""), ...);
		end
		return exp;
	end

	function addon:Debug(level, msg, ...)
		local msg = self:Format(msg, ...);
		local time = GetTime();
		if time == lastTime then
			timeAdjust = timeAdjust + 1;
			time = time + (timeAdjust / 1000000); -- micro second adjustments to avoid multiple events having the same time stamp
		else
			lastTime = time;
			timeAdjust = 0;
		end
		local e = {
			Type = level,
			Message = msg,
			Time = time - timeZero, -- calculate how long into the session the event occured at
		};
		table.insert(debugEvents, e);
	end

	function addon:DisplayDebug()
		if not frame then
			Debug_CreateFrame();
		end
		table.sort(debugEvents, function(a, b)
			return a.Time > b.Time;
		end);
		while #debugEvents > maxDebugEvents do
			table.remove(debugEvents, maxDebugEvents + 1);
		end
		frame:Show();
	end
end


